package com.yang.code_sample.performance_count.function;

import com.yang.code_sample.performance_count.entity.RequestInfo;
import com.yang.code_sample.performance_count.entity.RequestStat;
import com.yang.code_sample.performance_count.service.MetricsStorage;
import com.yang.code_sample.performance_count.utils.Aggregator;
import com.yang.code_sample.performance_count.utils.EmailSender;

import java.util.*;

/**
 * @Description: 邮件输出数据类
 * @Author: 杨 强
 * @CreateTime: 2022-10-13 17:27
 */
public class EmailReporter {
    // 发送邮件的间隔时间, 一天发送一次
    private static final Long DAY_HOURS_IN_SECONDS = 86400L;

    // 储存数据的接口
    private MetricsStorage metricsStorage;
    // 发送邮件类
    private EmailSender emailSender;
    // 发送邮件的地址
    private List<String> toAddresses;

    public EmailReporter(MetricsStorage metricsStorage) {
        this(metricsStorage, new EmailSender());
    }
    // 依赖注入
    public EmailReporter(MetricsStorage metricsStorage, EmailSender emailSender) {
        this.metricsStorage = metricsStorage;
        this.emailSender = emailSender;
    }

    // 添加邮件地址
    public void addToAddress(String address) {
        toAddresses.add(address);
    }

    // 发送数据
    public void startDailyReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date firstTime = calendar.getTime();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                long durationInMillis = DAY_HOURS_IN_SECONDS * 1000;
                long endTimeInMillis = System.currentTimeMillis();
                long startTimeInMillis = endTimeInMillis - durationInMillis;
                Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);
                Map<String, RequestStat> stats = new HashMap<>();
                for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
                    String apiName = entry.getKey();
                    List<RequestInfo> requestInfosPerApi = entry.getValue();
                    RequestStat requestStat = Aggregator.aggregate(requestInfosPerApi, durationInMillis);
                    stats.put(apiName, requestStat);
                }
                // TODO 杨强 格式化为html格式，并且发送邮件
            }
        }, firstTime, DAY_HOURS_IN_SECONDS * 1000);
    }
}
